import type { Component } from 'vue'
import { cloneDeep } from 'lodash-es'
import { POWER } from '@/constant'
import type { PowerType, Writable } from '@/types'
// import { NavigationStorageEnum } from '@/enum';
// import router from '@/router';

type PowerListType = typeof POWER.list
type SmallPowerListType = typeof POWER.smallList
/**
 * ## 获取当前页面功能权限
 * @template
 * ```typescript
 *  const { getPower } = usePagePower();
 *  const bol:boolean =getPower('add');
 * ```
 */
export function usePagePower() {
  const m: Record<PowerType, PowerListType[number]>
    = {} as any
  for (const n of POWER.list) {
    m[n.type] = n
  }

  /** ### 获取指定功能权限 */
  const getPower = (type: PowerType) => {
    const route = useRoute()
    const power = route.meta.power.split(',')

    if (route.meta.power === '0' || !route.meta.power)
      return true
    const key = m[type].key
    return power.includes(key)
  }

  /** ### 获取指定功能权限,依据图标 */
  const getPowerByIcon = (
    icon?: Component,
    func?: (list: PowerListType) => (Writable<
      SmallPowerListType[number]
    > & {
      icon: string[]
    })[],
  ) => {
    if (!icon)
      return false
    const iconName = icon.name?.toLocaleLowerCase()
    if (!iconName)
      return false
    const list = func
      ? func(cloneDeep(POWER.list))
      : POWER.list
    const type = (list as any[])?.find?.((item: any) =>
      (item.icon as unknown as string[]).includes(iconName),
    )?.type
    if (!type)
      return false
    return getPower(type)
  }
  return {
    getPower,
    getPowerByIcon,
  }
}
// function getRouter() {
//   const;
//   // const location = router.options.history.location;
//   // const locationMap = localStorage.getItem(
//   //   NavigationStorageEnum.INFO_MAP
//   // );
// }
